const fs = window.preload.fs;
const swig = window.preload.swig;
import { isHasDateTimePicker,isLongLabel,forMatDatePicker,returnBrack } from './swigTemplate.js';
import { treeToArray,onlyPageObj,arrayToTree } from '../tree.js';
 
function getProject(){
    return eval("(" + localStorage.getItem('projectConfig') + ")").nowProject;
}

async function readSwigTemplate(value){
    //读取swig模板
    const template = await fs.readFileSync(`${window.preload.dirname}output/swig_template/${value.type}.vue`,'utf8').toString();
    //渲染模版
    var html = swig.render(template, {
        locals: {
            'isHasDateTimePicker':isHasDateTimePicker,//是否有日期时间选择器判断
            'isLongLabel':isLongLabel,
            "forMatDatePicker":forMatDatePicker,
            "returnBrack":returnBrack,
            'pageConfig': value,
        }
    });
    return html;
}

async function readSwigRouter(value){
    //读取swig模板
    const template = await fs.readFileSync(`${window.preload.dirname}output/swig_template/router.js`,'utf8').toString();
    //渲染模版
    var html = swig.render(template, {
        locals: {
            'pageConfig': value,
        }
    });
    return html;
}

async function readSwigRouterConfig(value){
    //读取swig模板
    const template = await fs.readFileSync(`${window.preload.dirname}output/swig_template/routerConfig.js`,'utf8').toString();
    //渲染模版
    var html = swig.render(template, {
        locals: {
            'pageConfig': value,
        }
    });
    return html;
}

async function outputVueFile(value){
    let nowProject = getProject();
    //读取模板
    value.outPutType = "single";
    let html = await readSwigTemplate(value)
    //写入文件
    await fs.outputFileSync(`${window.preload.dirname}output/${nowProject.id}/preview/${value.name}.vue`, html);
}

async function outputSingleFile(nowItem,toSelectPath){
    let nowProject = getProject();
    try{
        await fs.copySync(`${window.preload.dirname}output/${nowProject.id}/preview/${nowItem.name}.vue`,`${toSelectPath}/${nowItem.name}.vue`);
        return { code:0,message:"导出成功" }
    } catch(err) {
        return { code:1,message:"导出失败" }
    }
}

async function outputProjectZip(nowItem,toSelectPath){
    let nowProject = getProject();
    try{
        await fs.copySync(`${window.preload.dirname}output/${nowProject.id}/zip/${nowProject.name}.zip`,`${toSelectPath}/${nowProject.name}.zip`);
        return { code:0,message:"导出成功" }
    } catch(err) {
        return { code:1,message:"导出失败" }
    }
}

async function compressing(){
    let nowProject = getProject();
    //删除原来的zip
    await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/zip/${nowProject.name}.zip`);
    await window.preload.compressing.zip.compressDir(`${window.preload.dirname}output/${nowProject.id}/project`,`${window.preload.dirname}output/${nowProject.id}/zip/${nowProject.name}.zip`);
}

async function projectMap(){
    let nowProject = getProject();
    //读取路由信息文件
    const routerConfig = await fs.readFile(`${window.preload.dirname}output/${nowProject.id}/router/routerConfig.json`,'utf8');
    let routerConfigObj = eval("(" + routerConfig + ")");
    let onlyPageRouter = onlyPageObj(treeToArray(routerConfigObj));
    //读取所有json文件，生成页面
    const result = await fs.readdir(`${window.preload.dirname}output/${nowProject.id}/json/`,'utf8');
    //去除detail文件夹名
    if(result.indexOf("detail") != -1){
        result.splice(result.indexOf("detail"),1);
    }
    //从临时文件进行统一删除
    await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/project/src/view`);
    //设置页面
    result.forEach(async(item) => {
        const resultJson = await fs.readFileSync(`${window.preload.dirname}output/${nowProject.id}/json/${item}`,'utf8');
        //去除item后缀
        let name = item.split(".")[0];
        //读取模板
        let value = eval('(' + resultJson + ')');
        value.outPutType = "project";
        value.name = name;
        let html = await readSwigTemplate(value)
        //将模版写入到project下到view下面
        let outputFileRouterInfo = onlyPageRouter[name];
        if(outputFileRouterInfo.path.split('/').length == 2){
            await fs.outputFileSync(`${window.preload.dirname}output/${nowProject.id}/project/src/view/${outputFileRouterInfo.path}/index.vue`, html);
        }else{
            await fs.outputFileSync(`${window.preload.dirname}output/${nowProject.id}/project/src/view/${outputFileRouterInfo.path}.vue`, html);
        }
    });
    //将默认文件复制过去
    await fs.copySync(`${window.preload.dirname}output/template/project/src/view/`,`${window.preload.dirname}output/${nowProject.id}/project/src/view/`);
}

async function projectDetialMap(){
    let nowProject = getProject();
    //读取路由信息文件
    const routerConfig = await fs.readFile(`${window.preload.dirname}output/${nowProject.id}/router/routerDetail.json`,'utf8');
    if(routerConfig == '[]'){
        return;
    }
    let routerConfigObj = eval("(" + routerConfig + ")");
    let onlyPageRouter = onlyPageObj(routerConfigObj);
    //读取所有json文件，生成页面
    const result = await fs.readdir(`${window.preload.dirname}output/${nowProject.id}/json/detail/`,'utf8');
    result.forEach(async(item) => {
        const resultJson = await fs.readFileSync(`${window.preload.dirname}output/${nowProject.id}/json/detail/${item}`,'utf8');
        //去除item后缀
        let name = item.split(".")[0];
        //读取模板
        let value = eval('(' + resultJson + ')');
        value.name = name;
        value.outPutType = "project";
        let html = await readSwigTemplate(value);
        //将模版写入到project下到view下面
        let outputFileRouterInfo = onlyPageRouter[`detail/${name}`];
        if(outputFileRouterInfo.path.split('/').length == 2){
            await fs.outputFileSync(`${window.preload.dirname}output/${nowProject.id}/project/src/view/${outputFileRouterInfo.path}/index.vue`, html);
        }else{
            await fs.outputFileSync(`${window.preload.dirname}output/${nowProject.id}/project/src/view/${outputFileRouterInfo.path}.vue`, html);
        }
    })
}

async function projectMapRouter(){
    let nowProject = getProject();
    //生成路由文件
    const routerConfigJson = await fs.readFileSync(`${window.preload.dirname}output/${nowProject.id}/router/routerConfig.json`,'utf8');
    const routerDetailJson = await fs.readFileSync(`${window.preload.dirname}output/${nowProject.id}/router/routerDetail.json`,'utf8');
    let routerConfig = eval('(' + routerConfigJson + ')');
    let routerDetail = eval('(' + routerDetailJson + ')');
    let routerConfigArr = treeToArray(routerConfig);
    let onlyPageRouter = onlyPageObj(routerConfigArr);
    routerDetail.forEach(item => {
        item.fatherPath = onlyPageRouter[item.belongTo].fatherPath;
        delete item.belongTo;
        item.name = item.name.split("detail/")[1];
        routerConfigArr.push(item);
    });
    let newRouterConfig = arrayToTree(routerConfigArr);
    var routerModuleName = [];
    newRouterConfig.forEach(async(item) => {
        let useItem = [];
        useItem.push(item);
        let forMatRouter = JSON.stringify(useItem).replace(/"\(\) /g,"()").replace(/.vue'\)"/g,".vue')");
        let name = item.path.split("/")[1];
        routerModuleName.push(name);
        let router = await readSwigRouter(forMatRouter);
        //写入到router的modules下
        await fs.outputFileSync(`${window.preload.dirname}output/${nowProject.id}/project/src/router/modules/${name}.js`, router);
    });
    let routerSideBar = await readSwigRouterConfig(routerModuleName);
    //写入到router的routerConfig.js
    await fs.outputFileSync(`${window.preload.dirname}output/${nowProject.id}/project/src/router/routerConfig.js`, routerSideBar);
}

export{
    outputVueFile,
    outputSingleFile,
    compressing,
    outputProjectZip,
    projectMap,
    projectDetialMap,
    projectMapRouter
}